﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI.WebControls;
using System.Web.UI;

namespace FlashNotification
{
    public class Flash : WebControl
    {

       
        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);

            // make sure that there is only one flash message on the current page
            if (GetCurrent(Page) != null)
                throw new InvalidOperationException("Only one Flash control instance is allowed on the current page.");

            // keep a reference to this flash instance
            Page.Items[typeof(Flash)] = this;
        }


     
        public static Flash GetCurrent(System.Web.UI.Page page)
        {
            if (page == null)
                throw new ArgumentNullException("page");

            return (Flash)page.Items[typeof(Flash)];
        }


      
        public string Notice
        {
            get;
            set;
        }

     
        public string Error
        {
            get;
            set;
        }


        public string Success
        {
            get;
            set;
        }


         public string Info
        {
            get;
            set;
        }


        protected override HtmlTextWriterTag TagKey
        {
            get
            {
                return HtmlTextWriterTag.Div;
            }
        }


         protected override void Render(HtmlTextWriter writer)
        {
            if (!string.IsNullOrEmpty(Notice) ||
                !string.IsNullOrEmpty(Error) ||
                !string.IsNullOrEmpty(Success) ||
                !string.IsNullOrEmpty(Info) )
            {
                base.Render(writer);
            }
        }


          protected override void RenderContents(HtmlTextWriter writer)
        {
            RenderMessageConditional(writer, "notice", Notice);
            RenderMessageConditional(writer, "error", Error);
            RenderMessageConditional(writer, "success", Success);
            RenderMessageConditional(writer, "info", Info);
        }


        private static void RenderMessageConditional(HtmlTextWriter writer, string className, string message)
        {
            if (string.IsNullOrEmpty(message)) return;

            writer.AddAttribute(HtmlTextWriterAttribute.Class, className);
            writer.RenderBeginTag(HtmlTextWriterTag.Div);
            writer.WriteEncodedText(message);
            writer.RenderEndTag(); // div
        }


    
    }
}